/**
 * Created by wangle on 2018/4/17.
 */
qui(
    function (require, exports, module) {
        RecordCol.Grid = function (options) {
            this.dao = RecordCol.Dao;
            this.config = RecordCol.Config;
            this.util = RecordCol.Util;
            this.task = RecordCol.Task;
            this.options = options || {};
        };
        Com.inherits(RecordCol.Grid, Ancestor.Grid).extend({
            doInit: function () {
                var self = this;
                var taskArr = [];
                taskArr.push(self.task.getLegoCategory("lego_category"))
                $.each(taskArr, function (index, element) {
                    EpgWeb.ajaxQueue.push(element.regName, element.options);
                })

                EpgWeb.ajaxQueue.afterLoadComplete(function () {
                    self.bindEvent();
                    self.initSuggest();
                    self.initGrid();
                    self.initSelect();
                    self.initDlg();
                    self.initAuthDlg();

                    var urlParams = self.getUrlParam();
                    if(urlParams['channelId'] && urlParams['channelName']){
                        self.query(urlParams['channelId']);
                        $('input[name="LIKES_col.channelName"]').val(urlParams['channelName']);
                    }else{
                        self.query();
                    }
                })
                EpgWeb.ajaxQueue.startLoad();
            },
            bindEvent: function () {
                var self = this;
                var parentDom = $("form[role=addForm]");
                $("button[name=add_col_btn]").bind("click", function (event) {
                    RecordCol.Util.sendAddColPlan();
                    $(".ui-dialog-title").html("新建栏目");
                })
                $("button[name=edit_col_btn]").bind("click", function (event) {
                    RecordCol.Util.sendEditColPlan();
                    $(".ui-dialog-title").html("新建栏目");
                })
                $("button[name=cancel_btn]").bind("click", function (event) {
                    $("form[role=addForm]").dialog("close")
                    $(".ui-dialog-title").html("新建栏目");
                })

                $("button[name=open_new_dlg_btn]").bind("click", function (event) {
                    $("form[role=addForm]").dialog("open");
                    $("form[role=addForm]")[0].reset();
                    var urlParams = self.getUrlParam();
                    if(urlParams['channelId'] && urlParams['channelName']){
                        $("form[role=addForm]").find("input[name=channel_name]").suggest("setValue", {id: urlParams['channelId'], label: urlParams['channelName']}).attr('disabled','disabled');
                    }
                    parentDom.find("button[name=add_col_btn]").show();
                    parentDom.find("button[name=edit_col_btn]").hide();

                })

                $("button[name=query_btn]").bind("click", function (event) {
                    self.query();
                })
                
                $("button[name=queryA]").bind("click", function(){
                    $("form[role=authForm]").dialog("open");
                    $("#ui-id-7").html('版权查询');
                    $("input[name=pcrName]").val("");
                    $("#authList").jqGrid("clearGridData");
                });

                $("button[name=queryAuth]").bind("click", function(){
                    self.authQuery();
                });

            },

            initSuggest: function () {
                var channelSuggest = {
                    options: {
                        ajaxSettings: {
                            beforeSend: function (request) {
                                var authBase = Ancestor.Util.getAuth("/record/channel/list");
                                request.setRequestHeader('Sign', authBase.sign);
                                request.setRequestHeader("Time", authBase.clientTime);
                                request.setRequestHeader("From", authBase.from);
                                request.setRequestHeader("UserName", (auth.baseInfo.authInfo == null) ? "" : escape(auth.baseInfo.authInfo.userName).toLocaleLowerCase().replace(/%u/gi, '\\u'));
                            }
                        },
                        source: RecordCol.urlConfig.getRecordChannelUrl,
                        method: "post",
                        autoFilter: false,
                        autoFocus: false,
                        multiple: false,
                        parseValue: function () {
                            var val = this.element.val(),
                                ret = []
                            return ret;
                        },
                        getParam: function (term) {
                            var jsonObj = {'LIKES_channelName': $.trim(term), 'NEQI_status': 0};
                            return {"dataMode": "simple", paramsObj: JSON.stringify(jsonObj)}
                        },
                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = json.data == null ? null : json.data;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data.result, function (item) {
                                itemData = {};
                                itemData[options.valueKey] = item["id"];
                                itemData[options.labelKey] = item["channelName"]
                                ret.push(itemData);
                            });
                            return ret;
                        },
                        template: function (item) {
                            return item.label;
                        }
                    }
                }

                var colSuggest = {
                    options: {
                        ajaxSettings: {
                            beforeSend: function (request) {
                                var authBase = Ancestor.Util.getAuth("/recordRPC/col/list");
                                request.setRequestHeader('Sign', authBase.sign);
                                request.setRequestHeader("Time", authBase.clientTime);
                                request.setRequestHeader("From", authBase.from);
                                request.setRequestHeader("UserName", (auth.baseInfo.authInfo == null) ? "" : escape(auth.baseInfo.authInfo.userName).toLocaleLowerCase().replace(/%u/gi, '\\u'));
                            }
                        },
                        source: "/api/recordRPC/col/list",
                        method: "post",
                        autoFilter: false,
                        autoFocus: false,
                        multiple: false,
                        parseValue: function () {
                            var val = this.element.val(),
                                ret = []
                            return ret;
                        },
                        getParam: function (term) {
                            var jsonObj = {LIKES_colName: $.trim(term)};
                            return {"dataMode": "simple", paramsObj: JSON.stringify(jsonObj)}
                        },
                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = json.data == null ? null : json.data;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data.result, function (item) {
                                itemData = {};
                                itemData[options.valueKey] = item["id"];
                                itemData[options.labelKey] = item["colName"]
                                ret.push(itemData);
                            });
                            return ret;
                        },
                        template: function (item) {
                            return item.label;
                        }
                    }
                }

                colSuggest.options.clearInvalid = false;
                $('input[name="LIKES_col.colName"]').suggest(colSuggest.options);
                $("input[name=channel_name]").suggest(channelSuggest.options);
                channelSuggest.options.clearInvalid = false;
                $('input[name="LIKES_col.channelName"]').suggest(channelSuggest.options);


            },
            initGrid: function (options) {
                var orOpt = options;
                var self = this;
                self.$grid = self.options.$grid;
                var params = self.getParam();

                var gridConfig = self.getGridConfig(self.config.COL_DATA_LIST);
                options = $.extend(true, {
                    mtype: 'post',
                    postData: $.extend(true, {}, params)
                }, gridConfig, options);
                self.$grid.jqGrid(options);

                var $authGrid = $("#authList");

                gridConfig = self.getGridConfig(self.config.AUTH_DATA_LIST, self.config.TABLE_COLMODEL_AUTH_CONFIG);
                orOpt = $.extend(true, {
                    mtype: 'get',
                }, gridConfig, orOpt);
                $authGrid.jqGrid(orOpt);
            },
            query: function (channelId,callback) {
                var self = this;
                var $grid = self.$grid;
                var params = self.getParam();
                var urlParams = self.getUrlParam();

                if(channelId){
                    var pp = JSON.parse(params['paramsObj']);
                    pp['EQI_channelId'] = channelId;
                    params ={'paramsObj': JSON.stringify(pp)} ;
                }

                var parentDom = $("form[role=addForm]");
                $(".ui-dialog-title").html("新建栏目");
                params.sortType = "desc";
                $grid.jqGrid('setGridParam', {
                    page: 1,
                    datatype: "json",
                    postData: params
                }).trigger('reloadGrid');
            },


            getParam: function () {
                var params = {};
                var inputArr = $('form[role="queryForm"]').find("input[role=query-text]")
                $.each(inputArr, function (i, element) {
                    if (element.value.trim().length > 0) {
                        params [$(element).attr("name")] = element.value.trim()
                    }
                });
                var selectArr = $('form[role="queryForm"]').find("select[role=query-select]")
                $.each(selectArr, function (i, element) {
                    if (element.name != "query-repeat-code") {
                        if (element.value.trim().length > 0) {
                            params [$(element).attr("name")] = element.value.trim()
                        }
                    }
                });
                params["EQI_col.status"] = 1;
                return {paramsObj: JSON.stringify(params)};
            },
            initSelect: function () {
                var resultData = RecordCol.Dao.getDataByName("lego_category");
                var filterArr = [];
                if (resultData != null) {
                    $.each(resultData.data, function (i, element) {
                        if (element.categoryConfig != null && element.categoryConfig.isIntoSearch == 1) {
                            filterArr.push({key: element.id, val: element.name})
                        }
                    })
                    var selectJDom = $("select[name='category_id']");
                    $("<option value=''></option>").appendTo(selectJDom);
                    $.each(filterArr, function (index, obj) {
                        $("<option>", {
                            value: obj.key,
                            html: obj.val
                        }).appendTo(selectJDom);
                    });
                }
            },
            initDlg: function () {
                $("form[role=addForm]").dialog({
                    title: "新建栏目",
                    autoOpen: false,
                    height: 400,
                    width: 800,
                    modal: true,
                });
            },

            initAuthDlg: function () {
                $("form[role=authForm]").dialog({
                    autoOpen: false,
                    height: 600,
                    width: 1200,
                    modal: true,
                })
            },

            initModifyDlg: function (type) {
                if (type == "edit") {

                } else if (type == "add") {

                }
            },
            getUrlParam: function(){
                var url = location.href;
                var params = {};
                if(url.indexOf('?')!=-1) {
                    var info = url.split('?')[1].split('&');
                    var channelId = info[0].split('=')[1];
                    var channelName = decodeURI(info[1].split('=')[1]);
                    params['channelId'] = channelId;
                    params['channelName'] = channelName;
                }

                return params;
            },

            authQuery: function (channelId,callback) {
                var self = this;
                var $grid = $("#authList");
                var self = this;
                var pcrName = $('input[name="pcrName"]').val().trim();
                if(!pcrName || pcrName == ''){
                    RecordCol.Util.logTips({theme: "error", content: "版权名称不能为空"});
                    return;
                }

                $grid.jqGrid('setGridParam', {
                    page: 1,
                    datatype: "json",
                    postData: {name:pcrName}
                }).trigger('reloadGrid');
            },
        });
    }
);